import { join } from "path";
import { app } from "electron";
import knex from "knex";

function insertSortingData(data: SortingData[]) {
  
}

export function initDbIpc() {
  const db = knex({
    client: "sqlite3",
    useNullAsDefault: true,
    connection: { filename: join(app.getPath("userData"), "./data.db") }
  });
  // 创建批次信息表
  db.schema.hasTable("batch").then((exist) => {
    if (exist) return;
    return db.schema.createTable("batch", (table) => {
      table.increments("id", { primaryKey: true }).comment("主键");
      table.string("type").comment("零件类型");
      table.string("material").comment("物料代码");
      table.boolean("doing").defaultTo(true).comment("是否加工中");
      table.dateTime("createAt", { useTz: true }).defaultTo(db.fn.now()).comment("批次开始时间");
    });
  });
  // 创建批次信息表
  db.schema.hasTable("execute").then((exist) => {
    if (exist) return;
    return db.schema.createTable("execute", (table) => {
      table.increments("id", { primaryKey: true }).comment("主键");
      table.string("judge").comment("综合判定");
      table.dateTime("createAt", { useTz: true }).defaultTo(db.fn.now()).comment("零件加工时间");
      table.integer("batchId").unsigned();
      table.foreign("batchId").references("batch.id");
    });
  });
  // 创建零件信息表
  db.schema.hasTable("measure").then((exist) => {
    if (exist) return;
    return db.schema.createTable("measure", (table) => {
      table.increments("id", { primaryKey: true }).comment("主键");
      table.string("field").comment("测量字段");
      table.float("value").comment("测量值");
      table.string("grade").comment("零件档次");
      table.integer("executeId").unsigned();
      table.foreign("executeId").references("execute.id");
    });
  });
}
